﻿using AutoMapper;
using CarAppDomain.CarParts.Entities;
using CarAppDomain.CarParts.IRepository;
using CarAppDomain.CarType.Entities;
using CarAppDomain.CarType.IRepository;
using CarAppDomain.CarType.IService;
using CarAppDto.CarParts.CarPartsDtos;
using CarAppDto.CarType.CarTypeDtos;
using CarAppDto.CarType.VehicleSeriesDtos;
using CarAppDto.Dtos;
using D.Util.UtilCache;
using D.UtilCore.Dtos;
using D.UtilCore.Utils;
using D.UtilSqlsugarOrm;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Writers;
using Org.BouncyCastle.Crypto;
using System.Linq.Expressions;

namespace CarAppDomain.CarType.Service
{
    public class VehicleSeriesService : BaseService<VehicleSeriesEntity>,IVehicleSeriesService
    {
        private readonly IMapper _mapper;
        private readonly ICacheService _cache;
        private readonly IVehicleSeriesEntityRepository _repository;
        private readonly IAreaEntityRepository _repositoryArea;
        private readonly ICountryEntityRepository _repositoryCountry;
        private readonly IBrandEntityRepository _repositorBrand;
        private readonly ICarPartsEntityRepository _repositoryCarParts;

        /// <summary>
        /// 构造注入
        /// </summary>
        public VehicleSeriesService(IMapper mapper, ICacheService cache, IVehicleSeriesEntityRepository repository, IAreaEntityRepository repositoryArea,
            ICountryEntityRepository repositoryCountry, IBrandEntityRepository repositorBrand, ICarPartsEntityRepository repositoryCarParts)
        {
            // 用于base方法
            base._baseDal = repository;
            this._repository = repository;
            _repositoryArea = repositoryArea;
            _repositoryCountry = repositoryCountry;
            _repositorBrand = repositorBrand;
            _cache = cache;
            _mapper = mapper;
            _repositoryCarParts = repositoryCarParts;
            }

        #region 增删改查


        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> AddVehicleSeriesAsync(ReqAddVehicleSeries reqModel)
        {
            var exists = await _repository.ExistsAsync(m => m.Code == reqModel.Code);
            if (exists)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "车系ID重复" };
            }
            if (!string.IsNullOrWhiteSpace(reqModel.SaleAreaId))
            {
                exists = await _repositoryArea.ExistsAsync(m => m.Id==reqModel.SaleAreaId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "销售区域不存在" };
                }
            }
            if (!string.IsNullOrWhiteSpace(reqModel.ManufacturingCountryId))
            {
                exists = await _repositoryCountry.ExistsAsync(m => m.Id == reqModel.ManufacturingCountryId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "制造国家不存在" };
                }
            }
            if (!string.IsNullOrWhiteSpace(reqModel.BrandId))
            {
                exists = await _repositorBrand.ExistsAsync(m => m.Id == reqModel.BrandId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "品牌信息不存在" };
                }
            }
            var insertEntity = _mapper.Map<ReqAddVehicleSeries,VehicleSeriesEntity>(reqModel);
            insertEntity.DeleteFlag = false;
            insertEntity.CreateTime = DateTime.Now;
            insertEntity.Id = Guid.NewGuid().ToString();

            var dbres = await _repository.AddAsync(insertEntity);
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> DeleteVehicleSeriesAsync(List<string> ids)
        {
            var dbres = await _repository.DeleteAsync(m => ids.Contains(m.Id));
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> UpdateVehicleSeriesAsync(ReqUpdateVehicleSeries reqModel)
        {

            var updateEntity = await _repository.GetModelAsync(m => m.Id == reqModel.Id);
            if (updateEntity == null)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "该信息不存在" };
            }
            var exists = await _repository.ExistsAsync(m => m.Code == reqModel.Code && m.Id != reqModel.Id);
            if (exists)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "车系ID重复" };
            }
            if (!string.IsNullOrWhiteSpace(reqModel.SaleAreaId))
            {
                exists = await _repositoryArea.ExistsAsync(m => m.Id == reqModel.SaleAreaId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "销售区域不存在" };
                }
            }
            if (!string.IsNullOrWhiteSpace(reqModel.ManufacturingCountryId))
            {
                exists = await _repositoryCountry.ExistsAsync(m => m.Id == reqModel.ManufacturingCountryId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "制造国家不存在" };
                }
            }
            if (!string.IsNullOrWhiteSpace(reqModel.BrandId))
            {
                exists = await _repositorBrand.ExistsAsync(m => m.Id == reqModel.BrandId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "品牌信息不存在" };
                }
            }
            updateEntity.UpdateTime = DateTime.Now;
            updateEntity.UpdateUser = reqModel.UpdateUser;
            updateEntity.BrandId = reqModel.BrandId;
            updateEntity.Code= reqModel.Code;
            updateEntity.Name= reqModel.Name;
            updateEntity.EnglishName= reqModel.EnglishName;
            updateEntity.CarSeriesModel= reqModel.CarSeriesModel;
            updateEntity.SaleAreaId= reqModel.SaleAreaId;
            updateEntity.ManufacturingCountryId= reqModel.ManufacturingCountryId;
            updateEntity.ModelYearCode= reqModel.ModelYearCode;
            updateEntity.CatalogNo= reqModel.CatalogNo;
            updateEntity.VehicleSeriesBrevityCoding= reqModel.VehicleSeriesBrevityCoding;
            updateEntity.VehicleSeriesVersionName= reqModel.VehicleSeriesVersionName;
            updateEntity.VehicleSeriesVersionEnglishName= reqModel.VehicleSeriesVersionEnglishName;
            updateEntity.MarketingTime= reqModel.MarketingTime;
            updateEntity.DownTime= reqModel.DownTime;
            updateEntity.SaleStatus= reqModel.SaleStatus;
            updateEntity.SaleDownTime= reqModel.SaleDownTime;
            updateEntity.Image = reqModel.Image;
            var dbres = await _repository.UpdateAsync(updateEntity);
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<RepVehicleSeries>>> QueryVehicleSeriesListAsync(ReqQueryVehicleSeriesList reqModel)
        {
            Expression<Func<VehicleSeriesEntity, bool>> where = null;
            if (!string.IsNullOrEmpty(reqModel.Name))
            {
                where = where.And(m => m.Name.Contains(reqModel.Name));
            }

            if (!string.IsNullOrEmpty(reqModel.EnglishName))
            {
                where = where.And(m => m.EnglishName.Contains(reqModel.EnglishName));
            }

            if (!string.IsNullOrEmpty(reqModel.Code))
            {
                where = where.And(m => m.Code.Contains(reqModel.Code));
            }
            if (!string.IsNullOrEmpty(reqModel.CarSeriesModel))
            {
                where = where.And(m => m.CarSeriesModel.Contains(reqModel.CarSeriesModel));
            }
            if (!string.IsNullOrEmpty(reqModel.BrandId))
            {
                where = where.And(m => m.BrandId == reqModel.BrandId);
            }
            var dbres = await _repository.GetListAsync(where);           
            return dbres.GetResponse();
        }

        /// <summary>
        /// 获取用户分页
        /// </summary>
        /// <param name="reqQueryAdminPage"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageModel<RepVehicleSeries>>> QueryVehicleSeriesPagesAsync(ReqQueryVehicleSeriesPage reqQueryPage)
        {
            Expression<Func<VehicleSeriesEntity, bool>> where = null;
            if (!string.IsNullOrEmpty(reqQueryPage.Name))
            {
                where = where.And(m => m.Name.Contains(reqQueryPage.Name));
            }
            if (!string.IsNullOrEmpty(reqQueryPage.EnglishName))
            {
                where = where.And(m => m.EnglishName.Contains(reqQueryPage.EnglishName));
            }
            if (!string.IsNullOrEmpty(reqQueryPage.SaleAreaId))
            {
                where = where.And(m => m.SaleAreaId==reqQueryPage.SaleAreaId);
            }
            if (!string.IsNullOrEmpty(reqQueryPage.ManufacturingCountryId))
            {
                where = where.And(m => m.ManufacturingCountryId == reqQueryPage.ManufacturingCountryId);
            }
            if (reqQueryPage.IsDown!=null)
            {
                if(reqQueryPage.IsDown==true)
                     where = where.And(m => m.DownTime!=null);
                else
                    where = where.And(m => m.DownTime == null);
            }
            if (reqQueryPage.SaleStatus!=null)
            {
                where = where.And(m => m.SaleStatus == reqQueryPage.SaleStatus);
            }
            if (!string.IsNullOrEmpty(reqQueryPage.Code))
            {
                where = where.And(m => m.Code.Contains(reqQueryPage.Code));
            }
            if (!string.IsNullOrEmpty(reqQueryPage.CarSeriesModel))
            {
                where = where.And(m => m.CarSeriesModel.Contains(reqQueryPage.CarSeriesModel));
            }
            if (!string.IsNullOrEmpty(reqQueryPage.BrandId))
            {
                where = where.And(m => m.BrandId == reqQueryPage.BrandId);
            }
            Expression<Func<VehicleSeriesEntity, object>> order = null;
            bool orderByAsc = true;
            if (reqQueryPage.Sorts != null && reqQueryPage.Sorts?.Count != 0)
            {
                SortDto sortDtoFrist = reqQueryPage.Sorts.FirstOrDefault();
                string sortField = sortDtoFrist?.Field;
                string sortOrder = sortDtoFrist?.Sort;
                order = ExpressionUtil.GetOrderObjectExpression<VehicleSeriesEntity>(sortField, sortOrder, ref orderByAsc);
            }
            else
                order = m => m.CreateTime;

            var dbres = await _repository.GetOrderPagesAsync(reqQueryPage.PageSize, reqQueryPage.PageNo, where, order, orderByAsc);
            var res = new PageModel<RepVehicleSeries>()
            {
                PageNo = dbres.PageNo,
                PageSize = dbres.PageSize,
                TotalCount = dbres.TotalCount,
                TotalPage = dbres.TotalPage,
                Data = dbres.Data
            };
            return res.GetResponse();
        }

        /// <summary>
        /// 查询单个
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResult<RepVehicleSeries>> GetVehicleSeriesAsync(string id)
        {
            var dbres = await _repository.GetModelAsync(m => m.Id == id);
            var res = _mapper.Map<VehicleSeriesEntity, RepVehicleSeries>(dbres);
            return res.GetResponse();
        }

        #endregion

        #region 配件管理
        /// <summary>
        /// 添加配件
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<int>> AddCarParts(ReqCarPartsVehicleSeries model, string userId)
        {
            var updateEntity = await _repository.GetModelAsync(m => m.Id == model.VehicleSeriesId);
            if (updateEntity == null)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "该信息不存在" };
            }
            // AddCarPartsAsync;
            List<CarPartsVehicleSeriesEntity> carPartsVehiclesList = new List<CarPartsVehicleSeriesEntity>();
            foreach (var item in model.CarPartsList)
            {
                CarPartsVehicleSeriesEntity entity = new CarPartsVehicleSeriesEntity();
                entity.CarPartsId = item;
                entity.VehicleSeriesId = model.VehicleSeriesId;
                entity.CreateUser = userId;
                entity.CreateTime = DateTime.Now;
                carPartsVehiclesList.Add(entity);
            }

            var dbres = await _repository.AddCarPartsAsync(carPartsVehiclesList);
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 根据车型Id获取配件
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<RepCarParts>>> GetCarPartsListByVehicleSeries(ReqQueryCarPartsVehicleSeriesPage reqModel)
        {
            var dbres = await _repositoryCarParts.GetCarPartsListByVehicleSeries(reqModel.PageSize, reqModel.PageNo, reqModel.VehicleSeriesId);          
            return dbres.GetResponse();
        }

        /// <summary>
        /// 删除配件车系
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> DeleteCarParts(List<string> ids)
        {
            var dbres = await _repository.DeleteCarPartsAsync(ids);
            return dbres.NormalResponse();
        }

        #endregion
    }
}
